import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './zhibo.module.css';

// WebRTC配置
const rtcConfig = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'stun:stun1.l.google.com:19302' },
    { urls: 'stun:stun2.l.google.com:19302' },
    { urls: 'stun:stun3.l.google.com:19302' },
    { urls: 'stun:stun4.l.google.com:19302' },
    // 添加免费TURN服务器(如果需要NAT穿透)
    {
      urls: 'turn:numb.viagenie.ca',
      username: 'webrtc@live.com',
      credential: 'muazkh'
    }
  ]
};

// 直播观众端组件
const StreamViewer = ({ roomId = 'live-room-001', onConnectionChange }) => {
  const navigate = useNavigate();
  
  // 返回首页函数
  const goToHome = () => {
    navigate('/');
  };
  const [remoteStream, setRemoteStream] = useState(null);
  const [cameraStream, setCameraStream] = useState(null); // 新增摄像头流状态
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState(null);
  const [connectionStatus, setConnectionStatus] = useState('disconnected');
  const [isWatching, setIsWatching] = useState(false);
  const [iceState, setIceState] = useState('');
  const [audioEnabled, setAudioEnabled] = useState(true);
  const [audioStatus, setAudioStatus] = useState('等待音频');
  const [pipPos, setPipPos] = useState({ left: 20, top: 20 }); // 摄像头小窗口位置
  const [dragging, setDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [danmakuMessages, setDanmakuMessages] = useState([]); // 弹幕消息列表
  const [danmakuInput, setDanmakuInput] = useState(''); // 弹幕输入内容
  const [danmakuEnabled, setDanmakuEnabled] = useState(true); // 弹幕开关
  const [trackOccupancy, setTrackOccupancy] = useState(new Array(8).fill(0)); // 轨道占用时间
  
  // 签到相关状态
  const [hasCheckedIn, setHasCheckedIn] = useState(false); // 是否已签到
  const [checkInCount, setCheckInCount] = useState(0); // 签到人数
  const [forceUpdate, setForceUpdate] = useState(0); // 强制重新渲染
  const [clientId, setClientId] = useState(() => {
    // 从localStorage获取或生成新的客户端ID
    const savedClientId = localStorage.getItem('viewer_client_id');
    if (savedClientId) {
      return savedClientId;
    }
    const newClientId = 'client_' + Math.random().toString(36).substr(2, 9);
    localStorage.setItem('viewer_client_id', newClientId);
    return newClientId;
  }); // 客户端ID
  
  // 投票系统相关状态
  const [voteData, setVoteData] = useState({
    isActive: false,
    question: '',
    options: [],
    results: {},
    totalVotes: 0,
    hasVoted: false, // 当前用户是否已投票
    selectedOption: null // 当前用户选择的选项
  });
  const [showVotePanel, setShowVotePanel] = useState(true); // 是否显示投票面板
  
  const videoRef = useRef(null);
  const cameraVideoRef = useRef(null); // 新增摄像头video引用
  const wsRef = useRef(null);
  const peerConnectionRef = useRef(null);
  const audioContextRef = useRef(null);
  const previewRef = useRef(null); // 新增

  useEffect(() => {
    if (cameraStream && cameraVideoRef.current) {
      cameraVideoRef.current.srcObject = cameraStream;
    }
  }, [cameraStream]);

  // WebSocket连接
  const connectWebSocket = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;
    
    try {
      console.log('尝试连接WebSocket服务器...');
      // 使用当前页面的主机地址，而不是硬编码localhost
      const wsUrl = `ws://${window.location.hostname}:9000/room/${roomId}`;
      console.log('WebSocket连接地址:', wsUrl);
      const ws = new WebSocket(wsUrl);
      
      ws.onopen = () => {
        console.log('观众WebSocket连接成功');
        setConnectionStatus('connected');
        onConnectionChange?.('connected');
        
        // 通知服务器观众加入
        ws.send(JSON.stringify({
          type: 'viewer-join',
          roomId,
          clientId
        }));
      };
      
      ws.onmessage = async (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log('收到WebSocket消息:', message.type);
          await handleSignalingMessage(message);
        } catch (error) {
          console.error('处理信令消息失败:', error);
        }
      };
      
      ws.onclose = () => {
        console.log('观众WebSocket连接关闭');
        setConnectionStatus('disconnected');
        onConnectionChange?.('disconnected');
        // 自动重连
        if (isWatching) {
          setTimeout(connectWebSocket, 3000);
        }
      };
      
      ws.onerror = (error) => {
        console.error('观众WebSocket错误:', error);
        setConnectionStatus('error');
        onConnectionChange?.('error');
      };
      
      wsRef.current = ws;
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      setError(`WebSocket连接失败: ${error.message}`);
      setTimeout(connectWebSocket, 5000);
    }
  }, [roomId, onConnectionChange, isWatching, clientId]);

  // 处理信令消息
  const handleSignalingMessage = async (message) => {
    const { type, data, from } = message;
    
    switch (type) {
      case 'offer':
        console.log('收到offer, 来自:', from);
        await handleOffer(data, from);
        break;
      case 'ice-candidate':
        console.log('收到ICE候选');
        await handleIceCandidate(data);
        break;
      case 'stream-ended':
        handleStreamEnded();
        break;
      case 'streaming-started':
        console.log('直播已开始');
        break;
      case 'no-stream':
        console.log('当前房间没有直播');
        setError('当前房间没有直播');
        break;
      case 'danmaku':
        console.log('收到弹幕消息:', data);
        addDanmakuMessage(data);
        break;
      case 'broadcast-danmaku':
        console.log('收到广播弹幕:', data);
        // 避免重复显示自己发送的弹幕
        if (data.sender !== 'viewer') {
          addDanmakuMessage(data);
        }
        break;
      case 'check-in-success':
        console.log('签到成功:', data);
        if (data && typeof data.count === 'number') {
          setHasCheckedIn(true);
          setCheckInCount(data.count);
          setForceUpdate(prev => prev + 1);
          console.log('签到状态已更新: 已签到');
          // 强制重新渲染
          setTimeout(() => {
            console.log('强制更新签到成功状态');
            setHasCheckedIn(true);
            setForceUpdate(prev => prev + 1);
          }, 0);
        } else {
          console.error('签到成功消息格式错误:', data);
          // 如果消息格式错误，重置签到状态
          setHasCheckedIn(false);
          setForceUpdate(prev => prev + 1);
        }
        break;
      case 'check-in-stats':
        console.log('收到签到统计:', data);
        if (data && typeof data.count === 'number' && Array.isArray(data.users)) {
          setCheckInCount(data.count);
          const isUserCheckedIn = data.users.includes(clientId);
          setHasCheckedIn(isUserCheckedIn);
          setForceUpdate(prev => prev + 1);
          console.log('签到统计更新:', { count: data.count, users: data.users, clientId, isUserCheckedIn });
          // 强制重新渲染
          setTimeout(() => {
            console.log('强制更新签到统计状态');
            setHasCheckedIn(isUserCheckedIn);
            setForceUpdate(prev => prev + 1);
          }, 0);
        } else {
          console.error('签到统计消息格式错误:', data);
        }
        break;
      case 'check-in-reset':
        console.log('签到已重置');
        setHasCheckedIn(false);
        setCheckInCount(0);
        break;
      case 'vote-start':
        console.log('观众端收到投票开始消息:', data);
        console.log('投票数据详情:', {
          question: data.question,
          options: data.options,
          dataType: typeof data,
          hasQuestion: 'question' in data,
          hasOptions: 'options' in data
        });
        setVoteData(prev => ({
          ...prev,
          isActive: true,
          question: data.question || '',
          options: data.options || [],
          results: {},
          totalVotes: 0,
          hasVoted: false,
          selectedOption: null
        }));
        break;
      case 'vote-end':
        console.log('投票结束:', data);
        setVoteData(prev => ({
          ...prev,
          isActive: false,
          results: data.results || {},
          totalVotes: data.totalVotes || 0
        }));
        break;
      case 'vote-update':
        console.log('投票更新:', data);
        setVoteData(prev => ({
          ...prev,
          results: data.results || {},
          totalVotes: data.totalVotes || 0
        }));
        break;
      case 'vote-reset':
        console.log('投票重置');
        setVoteData({
          isActive: false,
          question: '',
          options: [],
          results: {},
          totalVotes: 0,
          hasVoted: false,
          selectedOption: null
        });
        break;
      case 'vote-success':
        console.log('投票成功:', data);
        setVoteData(prev => ({
          ...prev,
          hasVoted: true,
          selectedOption: data.selectedOption
        }));
        break;
      case 'vote-error':
        console.log('投票失败:', data);
        // 投票失败时重置投票状态
        setVoteData(prev => ({
          ...prev,
          hasVoted: false,
          selectedOption: null
        }));
        break;
      case 'error':
        console.error('服务器错误:', data?.message || '未知错误');
        console.log('错误消息详情:', { 
          message: data?.message, 
          includesSign: data?.message?.includes('签到'),
          includesAlreadySigned: data?.message?.includes('已签到过')
        });
        if (data?.message?.includes('签到')) {
          if (data?.message?.includes('已签到过')) {
            // 如果服务器说已经签到过，保持已签到状态
            setHasCheckedIn(true);
            setForceUpdate(prev => prev + 1);
            console.log('服务器确认已签到，保持已签到状态');
            // 强制重新渲染
            setTimeout(() => {
              console.log('强制更新签到状态');
              setHasCheckedIn(true);
              setForceUpdate(prev => prev + 1);
            }, 0);
          } else {
            // 其他签到错误，重置签到状态
            setHasCheckedIn(false);
            setForceUpdate(prev => prev + 1);
            console.log('签到失败，重置签到状态');
          }
        }
        setError(data?.message || '服务器错误');
        break;
      default:
        console.log('观众端未知消息类型:', type);
    }
  };

  // 初始化音频上下文
  const initAudioContext = () => {
    // 只有在用户交互后才创建音频上下文
    if (!audioContextRef.current) {
      try {
        audioContextRef.current = new (window.AudioContext || window.webkitAudioContext)();
        console.log('音频上下文已创建');
      } catch (error) {
        console.error('创建音频上下文失败:', error);
        return;
      }
    }
    
    if (audioContextRef.current && audioContextRef.current.state === 'suspended') {
      const resumeAudio = async () => {
        try {
          if (audioContextRef.current && audioContextRef.current.state === 'suspended') {
            await audioContextRef.current.resume();
            console.log('音频上下文已恢复');
          }
        } catch (error) {
          console.error('恢复音频上下文失败:', error);
          // 如果恢复失败，尝试重新创建
          try {
            audioContextRef.current = new (window.AudioContext || window.webkitAudioContext)();
            console.log('重新创建音频上下文成功');
          } catch (createError) {
            console.error('重新创建音频上下文失败:', createError);
          }
        }
      };
      
      resumeAudio();
    }
  };

  // 处理offer
  const handleOffer = async (offer, from) => {
    try {
      console.log('开始处理offer...');
      
      // 初始化音频上下文
      initAudioContext();
      
      // 如果已存在连接，先关闭
      if (peerConnectionRef.current) {
        peerConnectionRef.current.close();
        peerConnectionRef.current = null;
      }
      
      const peerConnection = new RTCPeerConnection(rtcConfig);
      
      // 处理远程流
      peerConnection.ontrack = (event) => {
        console.log('=== 接收到远程流 ===');
        console.log('事件详情:', event);
        const track = event.track;
        
        console.log('轨道信息:', {
          kind: track.kind,
          id: track.id,
          contentHint: track.contentHint,
          label: track.label,
          readyState: track.readyState
        });
        
        // 检查所有接收器，看看是否有摄像头轨道
        const allReceivers = peerConnection.getReceivers();
        console.log('所有接收器:', allReceivers.map(receiver => ({
          trackId: receiver.track?.id,
          trackKind: receiver.track?.kind,
          trackContentHint: receiver.track?.contentHint,
          trackLabel: receiver.track?.label
        })));
        
        // 检查摄像头轨道是否还存在
        const cameraTracks = allReceivers
          .map(receiver => receiver.track)
          .filter(track => track && track.kind === 'video' && 
            (track.contentHint === 'camera' || track._isCameraTrack === true ||
             track.label.includes('camera') || track.label.includes('Camera') ||
             track.label.includes('user') || track.label.includes('User')));
        
        console.log('检测到的摄像头轨道数量:', cameraTracks.length);
        console.log('当前摄像头流状态:', cameraStream ? '存在' : '不存在');
        
        // 如果没有摄像头轨道，但之前有摄像头流，则清除摄像头流
        if (cameraTracks.length === 0 && cameraStream) {
          console.log('🎥 摄像头轨道已移除，清除摄像头流');
          setCameraStream(null);
          return; // 不继续处理，因为这是轨道移除事件
        }
        
        // 根据轨道的contentHint判断是主屏幕还是摄像头
        if ((track.contentHint === 'camera' || track._isCameraTrack === true || 
             track.label.includes('camera') || track.label.includes('Camera') ||
             track.label.includes('user') || track.label.includes('User')) && 
            track.kind === 'video' && !cameraStream) {
          // 摄像头视频轨道
          console.log('🎥 检测到摄像头轨道，开始设置摄像头流');
          const cameraMediaStream = new MediaStream([track]);
          setCameraStream(cameraMediaStream);
          
          // 直接设置摄像头视频源
          if (cameraVideoRef.current) {
            console.log('设置摄像头视频元素srcObject');
            cameraVideoRef.current.srcObject = cameraMediaStream;
            // 设置摄像头视频为静音，避免自动播放被阻止
            cameraVideoRef.current.muted = true;
            cameraVideoRef.current.play().catch(err => {
              console.error('摄像头视频播放失败:', err);
              // 只有在不是中断错误时才重试
              if (err.name !== 'AbortError') {
                // 摄像头视频播放失败时，尝试静音播放
                cameraVideoRef.current.muted = true;
                cameraVideoRef.current.play().catch(err2 => {
                  console.error('摄像头视频静音播放也失败:', err2);
                });
              }
            });
          } else {
            console.warn('摄像头视频元素引用不存在');
          }
          
          // 添加调试信息
          console.log('✅ 摄像头流已设置，PIP窗口应该显示');
        } else if (track.kind === 'video' && !cameraStream) {
          // 检查是否有多个视频轨道，如果有，第二个可能是摄像头
          const allVideoTracks = peerConnection.getReceivers()
            .map(receiver => receiver.track)
            .filter(track => track && track.kind === 'video');
          
          console.log('视频轨道数量:', allVideoTracks.length);
          
          // 如果这是第二个视频轨道，且还没有设置摄像头流，则将其作为摄像头
          if (allVideoTracks.length >= 2 && !cameraStream && 
              allVideoTracks.indexOf(track) === 1) {
            console.log('🎥 检测到第二个视频轨道，将其作为摄像头流');
            const cameraMediaStream = new MediaStream([track]);
            setCameraStream(cameraMediaStream);
            
            if (cameraVideoRef.current) {
              console.log('设置摄像头视频元素srcObject');
              cameraVideoRef.current.srcObject = cameraMediaStream;
              cameraVideoRef.current.muted = true;
              cameraVideoRef.current.play().catch(err => {
                console.error('摄像头视频播放失败:', err);
                // 只有在不是中断错误时才重试
                if (err.name !== 'AbortError') {
                  // 摄像头视频播放失败时，尝试静音播放
                  cameraVideoRef.current.muted = true;
                  cameraVideoRef.current.play().catch(err2 => {
                    console.error('摄像头视频静音播放也失败:', err2);
                  });
                }
              });
            }
            
            console.log('✅ 摄像头流已设置，PIP窗口应该显示');
          } else {
            console.log('📺 检测到主屏幕轨道');
            // 主屏幕流（包含音频和主视频）
            // 获取所有轨道
            const allTracks = peerConnection.getReceivers().map(receiver => receiver.track).filter(track => track);
            const videoTracks = allTracks.filter(track => track.kind === 'video' && track.contentHint !== 'camera');
            const audioTracks = allTracks.filter(track => track.kind === 'audio');
            
            console.log(`设置主屏幕流 - 视频轨道: ${videoTracks.length}, 音频轨道: ${audioTracks.length}`);
            
            // 输出音频轨道信息
            audioTracks.forEach((track, index) => {
              console.log(`音频轨道 ${index}: ${track.label}, 状态: ${track.readyState}`);
            });
            
            // 更新音频状态信息
            if (audioTracks.length > 0) {
              setAudioStatus(`有音频 (${audioTracks.length} 轨道)`);
            } else {
              setAudioStatus('无音频轨道');
            }
            
            // 创建只包含主屏幕内容的流
            const mainTracks = [...videoTracks, ...audioTracks];
            if (mainTracks.length > 0) {
              const mainStream = new MediaStream(mainTracks);
              setRemoteStream(mainStream);
              setIsConnected(true);
              setError(null);
              
              // 直接设置视频源，不依赖状态更新
              if (videoRef.current) {
                videoRef.current.srcObject = mainStream;
                videoRef.current.muted = !audioEnabled;
                videoRef.current.volume = audioEnabled ? 1.0 : 0.0;
                console.log('主屏幕媒体元素srcObject已设置（包含音频）');
                
                // 确保音频播放
                videoRef.current.muted = !audioEnabled;
                
                // 尝试播放
                videoRef.current.play().catch(err => {
                  console.error('主屏幕媒体播放失败:', err);
                  
                  // 只有在不是中断错误时才显示错误提示
                  if (err.name !== 'AbortError') {
                    // 自动播放失败时，提示用户点击播放
                    setError('浏览器阻止了自动播放，请点击视频开始播放');
                    
                    // 添加点击事件监听器，让用户可以手动播放
                    const handleVideoClick = () => {
                      videoRef.current.play().then(() => {
                        setError(null);
                        videoRef.current.removeEventListener('click', handleVideoClick);
                      }).catch(err => {
                        console.error('手动播放失败:', err);
                      });
                    };
                    videoRef.current.addEventListener('click', handleVideoClick);
                  }
                });
              }
            }
          }
        } else {
          console.log('📷 检测到非视频轨道');
          // 处理非视频轨道，例如音频轨道
          if (track.kind === 'audio') {
            console.log(`音频轨道: ${track.label}, 状态: ${track.readyState}`);
            if (track.readyState === 'ended') {
              console.log('音频轨道已结束');
            }
          }
        }
      };
      
      // 处理ICE候选
      peerConnection.onicecandidate = (event) => {
        if (event.candidate && wsRef.current?.readyState === WebSocket.OPEN) {
          console.log('发送ICE候选到主播:', from);
          wsRef.current.send(JSON.stringify({
            type: 'ice-candidate',
            data: event.candidate,
            to: from
          }));
        }
      };
      
      // ICE连接状态变化
      peerConnection.oniceconnectionstatechange = () => {
        const state = peerConnection.iceConnectionState;
        console.log('ICE连接状态变更:', state);
        setIceState(state);
        
        if (state === 'failed' || state === 'disconnected' || state === 'closed') {
          console.log('ICE连接失败或断开, 状态:', state);
          if (isWatching) {
            // 尝试重新建立连接
            setTimeout(() => {
              console.log('尝试重新连接...');
              stopWatching();
              setTimeout(startWatching, 1000);
            }, 2000);
          }
        }
      };
      
      // 连接状态变化
      peerConnection.onconnectionstatechange = () => {
        console.log('连接状态:', peerConnection.connectionState);
        if (peerConnection.connectionState === 'disconnected' || 
            peerConnection.connectionState === 'failed') {
          setIsConnected(false);
          setRemoteStream(null);
        }
      };
      
      console.log('设置远程描述...');
      await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
      
      // 创建answer
      console.log('创建answer...');
      const answer = await peerConnection.createAnswer();
      await peerConnection.setLocalDescription(answer);
      
      // 发送answer
      if (wsRef.current?.readyState === WebSocket.OPEN) {
        console.log('发送answer到主播:', from);
        wsRef.current.send(JSON.stringify({
          type: 'answer',
          data: answer,
          to: from
        }));
      } else {
        console.error('WebSocket未连接，无法发送answer');
        setError('WebSocket未连接，无法建立直播');
      }
      
      peerConnectionRef.current = peerConnection;
      
    } catch (error) {
      console.error('处理offer失败:', error);
      setError(`连接失败: ${error.message}`);
    }
  };

  // 处理ICE候选
  const handleIceCandidate = async (candidate) => {
    if (peerConnectionRef.current) {
      try {
        console.log('添加远程ICE候选');
        await peerConnectionRef.current.addIceCandidate(new RTCIceCandidate(candidate));
      } catch (error) {
        console.error('添加ICE候选失败:', error);
      }
    } else {
      console.warn('PeerConnection不存在，无法添加ICE候选');
    }
  };

  // 处理直播结束
  const handleStreamEnded = () => {
    setRemoteStream(null);
    setCameraStream(null); // 清理摄像头流
    setIsConnected(false);
    setError('直播已结束');
    setAudioStatus('无音频');
    if (peerConnectionRef.current) {
      peerConnectionRef.current.close();
      peerConnectionRef.current = null;
    }
  };

  // 切换音频
  const toggleAudio = () => {
    const newState = !audioEnabled;
    setAudioEnabled(newState);
    
    if (videoRef.current) {
      videoRef.current.muted = !newState;
      videoRef.current.volume = newState ? 1.0 : 0.0;
      console.log(`音频已${newState ? '开启' : '关闭'}`);
      
      // 如果启用音频，尝试恢复音频上下文（只在用户交互后）
      if (newState) {
        // 延迟初始化音频上下文，确保在用户交互后
        setTimeout(() => {
          initAudioContext();
        }, 100);
      }
    }
  };

  // 画中画拖拽功能
  const onMouseDown = (e) => {
    setDragging(true);
    const rect = e.currentTarget.getBoundingClientRect();
    const offsetX = e.clientX - rect.left;
    const offsetY = e.clientY - rect.top;
    
    const onMouseMove = (e) => {
      if (previewRef.current) {
        const containerRect = previewRef.current.getBoundingClientRect();
        const newLeft = Math.max(0, Math.min(containerRect.width - 200, e.clientX - containerRect.left - offsetX));
        const newTop = Math.max(0, Math.min(containerRect.height - 150, e.clientY - containerRect.top - offsetY));
        setPipPos({ left: newLeft, top: newTop });
      }
    };
    
    const onMouseUp = () => {
      setDragging(false);
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };
    
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  };

  useEffect(() => {
    if (remoteStream && videoRef.current) {
      console.log('在useEffect中设置媒体源');
      videoRef.current.srcObject = remoteStream;
      
      // 确保音频播放
      videoRef.current.muted = !audioEnabled;
      videoRef.current.volume = audioEnabled ? 1.0 : 0.0;
      
      // 添加媒体加载事件处理
      const handleMediaLoaded = () => {
        console.log('媒体内容已加载');
        const videoTracks = remoteStream.getVideoTracks();
        const audioTracks = remoteStream.getAudioTracks();
        console.log(`媒体轨道状态 - 视频: ${videoTracks.length}, 音频: ${audioTracks.length}`);
        
        // 更新音频状态信息
        if (audioTracks.length > 0) {
          setAudioStatus(`有音频 (${audioTracks.length} 轨道)`);
        } else {
          setAudioStatus('无音频轨道');
        }
      };
      
      const handleMediaError = (err) => {
        console.error('媒体错误:', err);
      };
      
      const handleVolumeChange = () => {
        console.log('音量变化:', videoRef.current.volume, '静音:', videoRef.current.muted);
      };
      
      videoRef.current.addEventListener('loadedmetadata', handleMediaLoaded);
      videoRef.current.addEventListener('error', handleMediaError);
      videoRef.current.addEventListener('volumechange', handleVolumeChange);
      
      return () => {
        if (videoRef.current) {
          videoRef.current.removeEventListener('loadedmetadata', handleMediaLoaded);
          videoRef.current.removeEventListener('error', handleMediaError);
          videoRef.current.removeEventListener('volumechange', handleVolumeChange);
        }
      };
    }
  }, [remoteStream, audioEnabled]);

  // 处理摄像头流
  useEffect(() => {
    if (cameraStream && cameraVideoRef.current) {
      console.log('在useEffect中设置摄像头媒体源');
      cameraVideoRef.current.srcObject = cameraStream;
      
      const handleCameraLoaded = () => {
        console.log('摄像头媒体内容已加载');
      };
      
      const handleCameraError = (err) => {
        console.error('摄像头媒体错误:', err);
      };
      
      const handleCameraEnded = () => {
        console.log('摄像头流已结束');
        setCameraStream(null);
      };
      
      cameraVideoRef.current.addEventListener('loadedmetadata', handleCameraLoaded);
      cameraVideoRef.current.addEventListener('error', handleCameraError);
      cameraVideoRef.current.addEventListener('ended', handleCameraEnded);
      
      // 监听摄像头轨道的结束事件
      cameraStream.getTracks().forEach(track => {
        track.addEventListener('ended', handleCameraEnded);
      });
      
      return () => {
        if (cameraVideoRef.current) {
          cameraVideoRef.current.removeEventListener('loadedmetadata', handleCameraLoaded);
          cameraVideoRef.current.removeEventListener('error', handleCameraError);
          cameraVideoRef.current.removeEventListener('ended', handleCameraEnded);
        }
        cameraStream.getTracks().forEach(track => {
          track.removeEventListener('ended', handleCameraEnded);
        });
      };
    } else if (!cameraStream && cameraVideoRef.current) {
      // 清理摄像头视频元素
      console.log('清理摄像头视频元素');
      cameraVideoRef.current.srcObject = null;
    }
  }, [cameraStream]);

  // 定期检查摄像头轨道状态
  useEffect(() => {
    if (peerConnectionRef.current && cameraStream) {
      const checkCameraTracks = () => {
        const allReceivers = peerConnectionRef.current.getReceivers();
        const cameraTracks = allReceivers
          .map(receiver => receiver.track)
          .filter(track => track && track.kind === 'video' && 
            (track.contentHint === 'camera' || track._isCameraTrack === true ||
             track.label.includes('camera') || track.label.includes('Camera') ||
             track.label.includes('user') || track.label.includes('User')));
        
        if (cameraTracks.length === 0) {
          console.log('🎥 定期检查：摄像头轨道已移除，清除摄像头流');
          setCameraStream(null);
        }
      };
      
      const interval = setInterval(checkCameraTracks, 2000); // 每2秒检查一次
      
      return () => clearInterval(interval);
    }
  }, [cameraStream]);

  // 初始化音频上下文
  useEffect(() => {
    initAudioContext();
    
    // 添加键盘监听，按'M'键切换音频
    const handleKeyPress = (e) => {
      if (e.key === 'm' || e.key === 'M') {
        toggleAudio();
      }
    };
    
    document.addEventListener('keydown', handleKeyPress);
    
    return () => {
      document.removeEventListener('keydown', handleKeyPress);
      // 清理音频上下文
      if (audioContextRef.current) {
        audioContextRef.current.close().catch(err => {
          console.warn('关闭音频上下文失败:', err);
        });
      }
    };
  }, []);

  // 开始观看
  const startWatching = () => {
    console.log('开始观看直播...');
    setIsWatching(true);
    setConnectionStatus('connecting');
    onConnectionChange?.('connecting');
    
    // 在用户交互后初始化音频上下文
    setTimeout(() => {
      initAudioContext();
    }, 100);
    
    connectWebSocket();
  };

  // 停止观看
  const stopWatching = () => {
    setIsWatching(false);
    
    if (peerConnectionRef.current) {
      peerConnectionRef.current.close();
      peerConnectionRef.current = null;
    }
    
    if (wsRef.current) {
      wsRef.current.close();
      wsRef.current = null;
    }
    
    setRemoteStream(null);
    setCameraStream(null); // 清理摄像头流
    setIsConnected(false);
    setConnectionStatus('disconnected');
    setAudioStatus('无音频');
    onConnectionChange?.('disconnected');
  };

  // 弹幕相关函数
  const sendDanmaku = () => {
    if (!danmakuInput.trim() || wsRef.current?.readyState !== WebSocket.OPEN) {
      console.log('弹幕发送失败:', {
        hasInput: !!danmakuInput.trim(),
        wsState: wsRef.current?.readyState,
        wsOpen: wsRef.current?.readyState === WebSocket.OPEN
      });
      return;
    }
    
    const message = {
      type: 'danmaku',
      content: danmakuInput.trim(),
      timestamp: Date.now(),
      id: `danmaku-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      sender: 'viewer' // 标识发送者
    };
    
    console.log('发送弹幕:', message);
    console.log('WebSocket状态:', wsRef.current?.readyState);
    console.log('房间ID:', roomId);
    
    // 尝试两种不同的消息格式
    const wsMessage1 = {
      type: 'danmaku',
      data: message,
      roomId
    };
    
    const wsMessage2 = {
      type: 'danmaku',
      content: message.content,
      timestamp: message.timestamp,
      id: message.id,
      sender: message.sender,
      roomId
    };
    
    console.log('发送WebSocket消息格式1:', wsMessage1);
    console.log('发送WebSocket消息格式2:', wsMessage2);
    
    try {
      // 先尝试格式1
      wsRef.current.send(JSON.stringify(wsMessage1));
      console.log('弹幕发送成功 (格式1)');
      
      // 如果格式1不行，尝试格式2
      setTimeout(() => {
        try {
          wsRef.current.send(JSON.stringify(wsMessage2));
          console.log('弹幕发送成功 (格式2)');
        } catch (error) {
          console.error('弹幕发送失败 (格式2):', error);
        }
      }, 100);
      
    } catch (error) {
      console.error('弹幕发送失败 (格式1):', error);
    }
    
    // 立即添加到本地弹幕列表（自己发送的弹幕）
    addDanmakuMessage(message);
    setDanmakuInput('');
  };

  const handleDanmakuKeyPress = (e) => {
    if (e.key === 'Enter') {
      sendDanmaku();
    }
  };

  const addDanmakuMessage = (message) => {
    console.log('添加弹幕消息:', message);
    console.log('当前弹幕数量:', danmakuMessages.length);
    
    const currentTime = Date.now();
    
    // 智能选择可用轨道
    const findAvailableTrack = () => {
      const now = currentTime;
      for (let i = 0; i < 8; i++) {
        if (trackOccupancy[i] <= now) {
          return i;
        }
      }
      // 如果所有轨道都被占用，选择最早释放的轨道
      return trackOccupancy.indexOf(Math.min(...trackOccupancy));
    };
    
    const selectedTrack = findAvailableTrack();
    const speed = ['speed-slow', 'speed-normal', 'speed-fast'][Math.floor(Math.random() * 3)];
    const duration = speed === 'speed-fast' ? 9000 : speed === 'speed-slow' ? 15000 : 12000;
    
    // 为弹幕添加随机样式属性
    const enhancedMessage = {
      ...message,
      track: selectedTrack,
      speed: speed,
      size: Math.random() > 0.85 ? 'size-large' : Math.random() > 0.7 ? 'size-small' : '',
      delay: Math.random() * 1, // 随机延迟0-1秒
      isOwnMessage: message.sender === 'viewer' // 标识是否是自己发送的弹幕
    };
    
    console.log('增强后的弹幕消息:', enhancedMessage);
    
    // 更新轨道占用时间
    setTrackOccupancy(prev => {
      const newOccupancy = [...prev];
      newOccupancy[selectedTrack] = currentTime + duration + (enhancedMessage.delay * 1000);
      return newOccupancy;
    });
    
    setDanmakuMessages(prev => {
      const newMessages = [...prev, enhancedMessage];
      console.log('更新弹幕列表，新数量:', newMessages.length);
      return newMessages;
    });
    
    // 自动清理过期弹幕（保持最多50条）
    setTimeout(() => {
      setDanmakuMessages(prev => prev.filter(msg => msg.id !== enhancedMessage.id));
    }, duration + 2000);
  };

  const clearDanmaku = () => {
    setDanmakuMessages([]);
  };

  // 签到功能
  const sendCheckIn = () => {
    console.log('签到按钮被点击，当前状态:', { hasCheckedIn, clientId });
    
    if (hasCheckedIn) {
      alert('您已经签到过了！');
      return;
    }
    
    if (wsRef.current?.readyState !== WebSocket.OPEN) {
      alert('连接已断开，无法签到');
      return;
    }
    
    if (!clientId) {
      alert('客户端ID未生成，请稍后重试');
      return;
    }
    
    console.log('发送签到请求...');
    
    // 立即设置签到状态，防止重复点击
    setHasCheckedIn(true);
    setForceUpdate(prev => prev + 1);
    console.log('签到状态已设置为true');
    
    wsRef.current.send(JSON.stringify({
      type: 'check-in',
      roomId,
      clientId
    }));
  };

  // 重置签到状态（用于测试）
  const resetCheckInState = () => {
    localStorage.removeItem('viewer_client_id');
    setHasCheckedIn(false);
    setCheckInCount(0);
    setForceUpdate(prev => prev + 1);
    // 重新生成客户端ID
    const newClientId = 'client_' + Math.random().toString(36).substr(2, 9);
    localStorage.setItem('viewer_client_id', newClientId);
    setClientId(newClientId);
    console.log('签到状态已重置，新客户端ID:', newClientId);
  };

  // 投票系统相关函数
  const sendVote = (optionIndex) => {
    if (!voteData.isActive || voteData.hasVoted) {
      console.log('投票已结束或已投票');
      return;
    }
    
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      console.log('发送投票:', optionIndex);
      wsRef.current.send(JSON.stringify({
        type: 'vote',
        data: {
          optionIndex,
          clientId
        },
        roomId
      }));
    }
  };

  const resetVoteState = () => {
    setVoteData({
      isActive: false,
      question: '',
      options: [],
      results: {},
      totalVotes: 0,
      hasVoted: false,
      selectedOption: null
    });
    console.log('投票状态已重置');
  };

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      stopWatching();
    };
  }, []);

  // 监听用户交互，初始化音频上下文
  useEffect(() => {
    const handleUserInteraction = () => {
      console.log('检测到用户交互，初始化音频上下文');
      initAudioContext();
      // 移除监听器，避免重复调用
      document.removeEventListener('click', handleUserInteraction);
      document.removeEventListener('touchstart', handleUserInteraction);
    };
    
    document.addEventListener('click', handleUserInteraction);
    document.addEventListener('touchstart', handleUserInteraction);
    
    return () => {
      document.removeEventListener('click', handleUserInteraction);
      document.removeEventListener('touchstart', handleUserInteraction);
    };
  }, []);

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };
    
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  return (
    <div className={styles.app}>
      {/* 头部导航 */}
      <div className={styles.chatHeader}>
        <button 
          className={styles.backButton}
          onClick={goToHome}
          title="返回首页"
        >
          ← 返回
        </button>
        <div className={styles.headerInfo}>
          <h1 className={styles.chatTitle}>👀 直播观看端</h1>
          <p className={styles.roomInfo}>观众房间: {roomId}</p>
        </div>
      </div>
      
      {/* 主要内容区域 */}
      <div className={styles.mainContent}>
        <div className={styles.streamContainer}>
          <div className={styles.header}>
            <h2 className={styles.title}>直播观看</h2>
            <div className={styles.status}>
              <span className={`${styles.statusDot} ${styles[connectionStatus]}`}></span>
              <span>{isConnected ? '已连接' : connectionStatus === 'connected' ? '等待直播' : '未连接'}</span>
              {iceState && <span> (ICE: {iceState})</span>}
            </div>
          </div>
          
          {error && (
            <div className={styles.error}>
              {error}
              {error.includes('自动播放') && (
                <button 
                  className={styles.button}
                  style={{ marginLeft: '10px', padding: '5px 10px', fontSize: '12px' }}
                  onClick={() => {
                    if (videoRef.current) {
                      videoRef.current.play().then(() => {
                        setError(null);
                      }).catch(err => {
                        console.error('手动播放失败:', err);
                      });
                    }
                  }}
                >
                  点击播放
                </button>
              )}
            </div>
          )}
          
          {/* 摄像头状态显示 */}
          {isConnected && (
            <div className={styles.mediaInfo}>
              {cameraStream ? '🎥 摄像头已连接' : '📷 等待摄像头连接...'}
            </div>
          )}

          <div className={styles.controls}>
            <button 
              className={styles.button} 
              onClick={startWatching} 
              disabled={isWatching}
            >
              开始观看
            </button>
            <button 
              className={styles.button} 
              onClick={stopWatching} 
              disabled={!isWatching}
            >
              停止观看
            </button>
            <button 
              className={styles.button} 
              onClick={toggleAudio}
            >
              {audioEnabled ? '静音' : '取消静音'}
            </button>
            <span className={styles.audioStatus}>{audioStatus}</span>
            
            {/* 弹幕控制 */}
            <div className={styles.danmakuControls}>
              <button 
                className={styles.button} 
                onClick={() => setDanmakuEnabled(!danmakuEnabled)}
                style={{ 
                  backgroundColor: danmakuEnabled ? '#4CAF50' : '#f44336',
                  color: 'white'
                }}
              >
                {danmakuEnabled ? '弹幕开' : '弹幕关'}
              </button>
              <button 
                className={styles.button} 
                onClick={clearDanmaku}
                style={{ backgroundColor: '#ff9800', color: 'white' }}
              >
                清空弹幕
              </button>
            </div>
          </div>

          <div className={styles.preview} ref={previewRef}>
            {remoteStream ? (
              <>
                <video 
                  ref={videoRef} 
                  autoPlay 
                  playsInline
                  controls
                  className={styles.video}
                  muted={!audioEnabled}
                  volume={audioEnabled ? 1.0 : 0.0}
                  onError={(e) => console.error('媒体播放错误:', e)}
                  onLoadedMetadata={() => console.log('媒体元数据已加载')}
                  onCanPlay={() => console.log('媒体可以播放')}
                  onClick={() => {
                    if (videoRef.current && videoRef.current.paused) {
                      videoRef.current.play().then(() => {
                        setError(null);
                      }).catch(err => console.error('点击后播放失败:', err));
                    }
                  }}
                />
                
                {/* 摄像头画中画 */}
                {cameraStream && (
                  <div 
                    className={styles.pipContainer}
                    style={{
                      left: `${pipPos.left}px`,
                      top: `${pipPos.top}px`,
                      width: '200px',
                      height: '150px',
                      cursor: dragging ? 'grabbing' : 'grab'
                    }}
                    onMouseDown={onMouseDown}
                  >
                    <video 
                      ref={cameraVideoRef}
                      autoPlay
                      playsInline
                      muted
                      onError={(e) => console.error('摄像头视频播放错误:', e)}
                      onLoadedMetadata={() => console.log('🎥 摄像头视频元数据已加载')}
                      onCanPlay={() => console.log('🎥 摄像头视频可以播放')}
                    />
                    <div className={styles.pipLabel}>
                      摄像头
                    </div>
                  </div>
                )}
              </>
            ) : (
              <div className={styles.placeholder}>
                {isWatching ? '等待直播开始...' : '点击"开始观看"按钮连接直播间'}
              </div>
            )}
            
            {/* 弹幕显示区域 - 移到外部，确保始终显示 */}
            {danmakuEnabled && (
              <div className={styles.danmakuDisplay}>
                {/* 调试信息 */}
                <div style={{ 
                  position: 'absolute', 
                  top: '10px', 
                  left: '10px', 
                  background: 'rgba(0,0,0,0.7)', 
                  color: 'white', 
                  padding: '5px', 
                  borderRadius: '4px',
                  fontSize: '12px',
                  zIndex: 1000
                }}>
                  弹幕数量: {danmakuMessages.length} | 弹幕开关: {danmakuEnabled ? '开' : '关'}
                </div>
                
                {danmakuMessages.slice(-20).map((msg, index) => (
                  <div 
                    key={`viewer-${msg.id}-${index}-${msg.timestamp}`}
                    className={`${styles.danmakuItem} ${msg.speed ? styles[msg.speed] : ''} ${msg.size ? styles[msg.size] : ''} ${msg.isOwnMessage ? styles.ownMessage : ''}`}
                    style={{
                      top: `${(msg.track || 0) * 12 + 10}%`,
                      animationDelay: `${(msg.delay || 0) + index * 0.3}s`,
                      animationDuration: msg.speed === 'speed-fast' ? '9s' : msg.speed === 'speed-slow' ? '15s' : '12s'
                    }}
                  >
                    {msg.content}
                  </div>
                ))}
              </div>
            )}
            
            {/* 弹幕输入框 - 移到底部中间，更符合用户习惯 */}
            {danmakuEnabled && (
              <div style={{
                position: 'fixed',
                bottom: '20px',
                left: '50%',
                transform: 'translateX(-50%)',
                zIndex: 1001,
                display: 'flex',
                gap: '10px',
                background: 'rgba(0, 0, 0, 0.9)',
                padding: '12px 18px',
                borderRadius: '30px',
                backdropFilter: 'blur(15px)',
                boxShadow: '0 6px 20px rgba(0, 0, 0, 0.4)',
                border: '1px solid rgba(255, 255, 255, 0.15)',
                maxWidth: '90vw',
                minWidth: '300px'
              }}>
                                  <input
                    type="text"
                    value={danmakuInput}
                    onChange={(e) => setDanmakuInput(e.target.value)}
                    onKeyPress={handleDanmakuKeyPress}
                    placeholder="发送弹幕..."
                    style={{
                      background: 'rgba(255, 255, 255, 0.95)',
                      border: 'none',
                      borderRadius: '25px',
                      padding: '10px 18px',
                      fontSize: '15px',
                      color: '#333',
                      outline: 'none',
                      minWidth: '200px',
                      maxWidth: '300px',
                      flex: '1',
                      boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
                    }}
                    maxLength={50}
                  />
                <button 
                  onClick={sendDanmaku}
                  disabled={!danmakuInput.trim()}
                  style={{
                    background: 'linear-gradient(135deg, #4CAF50, #45a049)',
                    color: 'white',
                    border: 'none',
                    borderRadius: '25px',
                    padding: '10px 20px',
                    fontSize: '14px',
                    fontWeight: 'bold',
                    cursor: danmakuInput.trim() ? 'pointer' : 'not-allowed',
                    transition: 'all 0.3s ease',
                    opacity: danmakuInput.trim() ? 1 : 0.6,
                    whiteSpace: 'nowrap',
                    boxShadow: '0 2px 8px rgba(76, 175, 80, 0.3)',
                    transform: danmakuInput.trim() ? 'scale(1)' : 'scale(0.95)'
                  }}
                  onMouseEnter={(e) => {
                    if (danmakuInput.trim()) {
                      e.target.style.transform = 'scale(1.05)';
                      e.target.style.boxShadow = '0 4px 12px rgba(76, 175, 80, 0.4)';
                    }
                  }}
                  onMouseLeave={(e) => {
                    e.target.style.transform = danmakuInput.trim() ? 'scale(1)' : 'scale(0.95)';
                    e.target.style.boxShadow = '0 2px 8px rgba(76, 175, 80, 0.3)';
                  }}
                >
                  发送
                </button>
              </div>
            )}
            
            {/* 签到功能 */}
            <div style={{
              position: 'fixed',
              bottom: '80px',
              right: '20px',
              zIndex: 1000,
              display: 'flex',
              flexDirection: 'column',
              gap: '10px',
              maxWidth: '200px'
            }}>
              {/* 签到按钮 */}
              <button
                onClick={sendCheckIn}
                disabled={hasCheckedIn}
                style={{
                  padding: '10px 16px',
                  borderRadius: '20px',
                  border: 'none',
                  fontSize: '13px',
                  fontWeight: 'bold',
                  cursor: hasCheckedIn ? 'not-allowed' : 'pointer',
                  backgroundColor: hasCheckedIn ? '#9E9E9E' : '#4CAF50',
                  color: 'white',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
                  transition: 'all 0.3s ease',
                  whiteSpace: 'nowrap'
                }}
                title={`签到状态: ${hasCheckedIn ? '已签到' : '未签到'}`}
              >
                {hasCheckedIn ? '✅ 已签到' : '📝 签到'}
              </button>
              
              {/* 签到统计 */}
              <div style={{
                background: 'rgba(0,0,0,0.8)',
                color: 'white',
                padding: '6px 10px',
                borderRadius: '8px',
                fontSize: '11px',
                textAlign: 'center',
                whiteSpace: 'nowrap'
              }}>
                📊 {checkInCount} 人
              </div>
            </div>
            
            {/* 投票功能 */}
            {showVotePanel && (
              <div style={{
                position: 'fixed',
                top: '20px',
                right: '20px',
                zIndex: 1000,
                display: 'flex',
                flexDirection: 'column',
                gap: '10px',
                maxWidth: '280px'
              }}>
                {voteData.isActive ? (
                  <div style={{
                    background: 'rgba(233, 30, 99, 0.95)',
                    color: 'white',
                    padding: '15px',
                    borderRadius: '15px',
                    boxShadow: '0 6px 20px rgba(233, 30, 99, 0.5)',
                    backdropFilter: 'blur(10px)',
                    border: '1px solid rgba(255, 255, 255, 0.1)'
                  }}>
                    {/* 投票标题 */}
                    <div style={{
                      fontSize: '14px',
                      fontWeight: 'bold',
                      marginBottom: '10px',
                      textAlign: 'center'
                    }}>
                      🗳️ {voteData.question}
                    </div>
                    
                    {/* 投票选项 */}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                      {voteData.options.map((option, index) => {
                        const votes = voteData.results[index] || 0;
                        const percentage = voteData.totalVotes > 0 ? (votes / voteData.totalVotes * 100).toFixed(1) : 0;
                        const isSelected = voteData.selectedOption === index;
                        const isVoted = voteData.hasVoted;
                        
                        return (
                          <button
                            key={index}
                            onClick={() => sendVote(index)}
                            disabled={isVoted}
                            style={{
                              padding: '8px 12px',
                              borderRadius: '8px',
                              border: 'none',
                              fontSize: '12px',
                              cursor: isVoted ? 'not-allowed' : 'pointer',
                              backgroundColor: isSelected ? '#FF5722' : 'rgba(255,255,255,0.2)',
                              color: 'white',
                              textAlign: 'left',
                              transition: 'all 0.3s ease',
                              position: 'relative',
                              overflow: 'hidden'
                            }}
                            title={isVoted ? '已投票' : `选择: ${option}`}
                          >
                            <div style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              marginBottom: '4px'
                            }}>
                              <span>{option}</span>
                              <span style={{ fontSize: '10px', opacity: '0.8' }}>
                                {votes} 票 ({percentage}%)
                              </span>
                            </div>
                            
                            {/* 进度条 */}
                            <div style={{
                              width: '100%',
                              height: '3px',
                              background: 'rgba(255,255,255,0.2)',
                              borderRadius: '2px',
                              overflow: 'hidden'
                            }}>
                              <div style={{
                                width: `${percentage}%`,
                                height: '100%',
                                background: 'linear-gradient(90deg, #FF5722, #FF8A80)',
                                borderRadius: '2px',
                                transition: 'width 0.3s ease'
                              }} />
                            </div>
                            
                            {/* 投票状态指示 */}
                            {isSelected && (
                              <div style={{
                                position: 'absolute',
                                top: '4px',
                                right: '4px',
                                fontSize: '10px',
                                color: '#FF5722',
                                fontWeight: 'bold'
                              }}>
                                ✓
                              </div>
                            )}
                          </button>
                        );
                      })}
                    </div>
                    
                    {/* 投票状态 */}
                    <div style={{
                      fontSize: '11px',
                      textAlign: 'center',
                      marginTop: '8px',
                      opacity: '0.9'
                    }}>
                      {voteData.hasVoted ? '✅ 已投票' : '⏳ 等待投票'} | {voteData.totalVotes} 票
                    </div>
                  </div>
                ) : voteData.totalVotes > 0 ? (
                  <div style={{
                    background: 'rgba(233, 30, 99, 0.9)',
                    color: 'white',
                    padding: '12px',
                    borderRadius: '12px',
                    boxShadow: '0 4px 16px rgba(233, 30, 99, 0.4)',
                    backdropFilter: 'blur(4px)'
                  }}>
                    {/* 投票结果 */}
                    <div style={{
                      fontSize: '13px',
                      fontWeight: 'bold',
                      marginBottom: '8px',
                      textAlign: 'center'
                    }}>
                      🏆 投票结果
                    </div>
                    
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                      {voteData.options.map((option, index) => {
                        const votes = voteData.results[index] || 0;
                        const percentage = voteData.totalVotes > 0 ? (votes / voteData.totalVotes * 100).toFixed(1) : 0;
                        
                        return (
                          <div key={index} style={{
                            padding: '5px 7px',
                            borderRadius: '5px',
                            background: 'rgba(255,255,255,0.1)',
                            fontSize: '10px'
                          }}>
                            <div style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              marginBottom: '3px'
                            }}>
                              <span>{option}</span>
                              <span style={{ fontSize: '10px', opacity: '0.8' }}>
                                {votes} 票 ({percentage}%)
                              </span>
                            </div>
                            
                            <div style={{
                              width: '100%',
                              height: '3px',
                              background: 'rgba(255,255,255,0.2)',
                              borderRadius: '2px',
                              overflow: 'hidden'
                            }}>
                              <div style={{
                                width: `${percentage}%`,
                                height: '100%',
                                background: 'linear-gradient(90deg, #FF5722, #FF8A80)',
                                borderRadius: '2px'
                              }} />
                            </div>
                          </div>
                        );
                      })}
                    </div>
                    
                    <div style={{
                      fontSize: '9px',
                      textAlign: 'center',
                      marginTop: '6px',
                      opacity: '0.8'
                    }}>
                      {voteData.totalVotes} 票
                    </div>
                  </div>
                ) : (
                  <div style={{
                    background: 'rgba(233, 30, 99, 0.9)',
                    color: 'white',
                    padding: '12px',
                    borderRadius: '12px',
                    boxShadow: '0 4px 16px rgba(233, 30, 99, 0.4)',
                    backdropFilter: 'blur(4px)',
                    textAlign: 'center'
                  }}>
                    <div style={{ fontSize: '13px', fontWeight: 'bold', marginBottom: '4px' }}>
                      🗳️ 投票系统
                    </div>
                    <div style={{ fontSize: '11px', opacity: '0.8' }}>
                      等待主播开始投票...
                    </div>
                  </div>
                )}
                
                {/* 投票控制按钮 */}
                <button
                  onClick={() => setShowVotePanel(!showVotePanel)}
                  style={{
                    padding: '8px 12px',
                    borderRadius: '8px',
                    border: 'none',
                    fontSize: '12px',
                    cursor: 'pointer',
                    backgroundColor: 'rgba(0,0,0,0.9)',
                    color: 'white',
                    transition: 'all 0.3s ease',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.3)'
                  }}
                >
                  {showVotePanel ? '隐藏投票' : '显示投票'}
                </button>
              </div>
            )}
            
            {/* 可选：退出全屏按钮 */}
            {isFullscreen && (
              <button
                style={{ position: 'absolute', top: 10, right: 10, zIndex: 10 }}
                onClick={() => {
                  document.exitFullscreen().catch(err => {
                    console.error('退出全屏失败:', err);
                  });
                }}
              >退出全屏</button>
            )}
          </div>
          
          <div className={styles.tips}>
            <p>提示: 按'M'键可以快速切换音频开关</p>
            <p>如果听不到声音，请检查:</p>
            <ol>
              <li>确认主播开启了音频</li>
              <li>检查浏览器音量</li>
              <li>点击视频画面激活音频</li>
            </ol>
            
            {/* 调试信息 */}
            {isWatching && (
              <div style={{ marginTop: '20px', padding: '10px', background: '#f0f0f0', borderRadius: '8px' }}>
                <h4>调试信息:</h4>
                <p>连接状态: {connectionStatus}</p>
                <p>ICE状态: {iceState}</p>
                <p>主屏幕流: {remoteStream ? '已连接' : '未连接'}</p>
                <p>摄像头流: {cameraStream ? '已连接' : '未连接'}</p>
                <p>WebSocket: {wsRef.current?.readyState === WebSocket.OPEN ? '已连接' : '未连接'}</p>
                <p>PeerConnection: {peerConnectionRef.current ? '已创建' : '未创建'}</p>
                <p>签到状态: {hasCheckedIn ? '已签到' : '未签到'}</p>
                <p>签到人数: {checkInCount}</p>
                <p>投票状态: {voteData.isActive ? '进行中' : '未开始'}</p>
                <p>投票结果: {voteData.totalVotes} 票</p>
                <p>客户端ID: {clientId || '未生成'}</p>
                <button 
                  onClick={resetCheckInState}
                  style={{ 
                    marginTop: '10px', 
                    padding: '5px 10px', 
                    fontSize: '12px',
                    backgroundColor: '#ff4444',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer'
                  }}
                >
                  重置签到状态
                </button>
                <button 
                  onClick={resetVoteState}
                  style={{ 
                    marginTop: '5px', 
                    padding: '5px 10px', 
                    fontSize: '12px',
                    backgroundColor: '#E91E63',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer'
                  }}
                >
                  重置投票状态
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default StreamViewer;